import net.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;


/**
 * Created by zyh on 2017/3/2.
 */
public class HibernateTest {
    @Test
    public void configTest(){
        /*创建configuration实例*/
        Configuration configuration = new Configuration();
        /*自动加载配置文件*/
        configuration.configure("hibernate.cfg.xml");
        /*构建sessionFactory实例*/
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        /*session实例*/
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User user = new User();
        user.setUsername("123");
        user.setPassword("123");
        session.save(user);
        transaction.commit();
        session.close();

    }
    /*查询id为三的数据对象*/
    @Test
    public void getTest(){
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
       /* User user =(User) session.get(User.class,1);*/
        User user = null;
       /*条件查询*/
        user = (User) session.createQuery(
                "from User a where a.username = username and a.password=password")
                .setParameter(0,"username")
                .setParameter(1,"password")
                .uniqueResult();
        user.setPassword("123456");
       /*更新对象*/
        session.update(user);

        transaction.commit();
        session.close();
        System.out.println(user);
    }
}
